package geoway.bmf.keycloak.service;

import geoway.bmf.keycloak.client.KeycloakClient;
import geoway.bmf.keycloak.dto.LoginDto;
import geoway.bmf.keycloak.utils.OkHttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yrt
 * @description
 * @date 2022/11/23 11:06
 */

@Service
public class KeyCloakRemoteService {

    private final KeycloakClient keycloakClient;

    @Value("${keycloak.resource}")
    private  String clientId;

    @Value("${keycloak.auth-server-url}")
    private String keycloakUrl;

    @Value("${keycloak.realm}")
    private String realm;


    public KeyCloakRemoteService(KeycloakClient keycloakClient) {
        this.keycloakClient = keycloakClient;
    }

    public String userLogin(LoginDto loginDto){

//        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
//        map.add("grant_type", "password");
//        map.add("client_id", clientId);
//        map.add("username", loginDto.getUserName());
//        map.add("password", loginDto.getPassword());
//        Object login = keycloakClient.login("application/x-www-form-urlencoded",map);

        Map<String,String> headMap=new HashMap<>();
        headMap.put("Content-Type", "application/x-www-form-urlencoded");
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "password");
        map.put("client_id", clientId);
        map.put("username", loginDto.getUserName());
        map.put("password", loginDto.getPassword());

        String url=keycloakUrl+"/realms/"+realm+"/protocol/openid-connect/token";
        String post = OkHttpUtil.post(url, map, headMap);
        return post;
    }

}
